package com.villaday.idf.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.villaday.idf.R;
import com.villaday.idf.adapter3.HouseManageAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.LoadDialog;
import com.villaday.idf.custom.pop.HouseManagePop;
import com.villaday.idf.custom.pop.RefusePop;
import com.villaday.idf.model3.HashInfosEntity;
import com.villaday.idf.model3.HashStates;
import com.villaday.idf.model3.HashStatesEntity;
import com.villaday.idf.model3.StatesPostEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DateUtils;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class HouseManageActivity extends BaseActivity {


    @BindView(R.id.toolbar_back)
    ImageButton toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_next)
    TextView toolbarNext;
    @BindView(R.id.Line_view)
    View LineView;
    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.rv_hm)
    RecyclerView rvHm;
    @BindView(R.id.ll_hm_total)
    LinearLayout llHmTotal;
    @BindView(R.id.tv_hm_close)
    TextView tvHmClose;
    @BindView(R.id.tv_hm_manage)
    TextView tvHmManage;
    @BindView(R.id.tv_hm_house)
    TextView tvHmHouse;
    @BindView(R.id.tv_hm_date)
    TextView tvHmDate;
    @BindView(R.id.tv_hm_not)
    TextView tvHmNot;

    private HouseManageAdapter mHouseManageAdapter;
    private String mHouseId;
    private List<HashStatesEntity.BodyBean.MonthsBean> mMonths;
    private String mHouseName;
    private LoadDialog mLoadDialog;
    private HashInfosEntity.BodyBean mInfoBody;


    @Override
    protected int getViewResId() {
        return R.layout.activity_house_manage;
    }

    @Override
    protected void init() {
        super.init();
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        StatusBarUtil.setLightMode(this);
        showDialog();

        ToolBarUtil.initToolBar(toolbarText, "房态管理", new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        toolbarText.setBackgroundResource(R.color.colorBackground);
        toolbarNext.setTextColor(getResources().getColor(R.color.color718294));
        mHouseId = getIntent().getExtras().getString("houseId");
        mHouseName = getIntent().getExtras().getString("houseName");
        tvHmHouse.setText(mHouseName);
        tvHmDate.setText("更新时间：" + DateUtils.long2Data(System.currentTimeMillis()));
        initRecycle();
        getInfo();
        getDetails();
    }


    private void getInfo() {
        Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, String.format(Constant.URL.hashInfos, SharedPreferencesUtil.getRoleInfoId(this)), map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    HashInfosEntity hashInfosEntity = new Gson().fromJson(json, HashInfosEntity.class);
                    if (hashInfosEntity.getCode().equals(Constant.Strings.SUC)) {
                        mInfoBody = hashInfosEntity.getBody();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    private void getDetails() {
        Map<String, String> map = new HashMap<>();
        map.put("month", DateUtils.getStringMouth(System.currentTimeMillis()));
        OkHttpUtil.getJSON(this, String.format(Constant.URL.hashStates, SharedPreferencesUtil.getRoleInfoId(this), mHouseId), map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    dismissDialog();
                    if (!TextUtils.isEmpty(json)) {
                        HashStatesEntity hashStatesEntity = new Gson().fromJson(json, HashStatesEntity.class);
                        if (hashStatesEntity.getCode().equals(Constant.Strings.SUC) && hashStatesEntity.getBody() != null) {
                            tvHmNot.setVisibility(View.GONE);
                            rvHm.setVisibility(View.VISIBLE);
                            mMonths = hashStatesEntity.getBody().getMonths();
                            mHouseManageAdapter.setData(mMonths);

                            tvHmClose.setEnabled(false);
                            tvHmManage.setEnabled(false);
                            tvHmClose.setTextColor(getResources().getColor(R.color.colorTextLight));
                            tvHmManage.setBackgroundResource(R.drawable.shape_gradient_7f_8e_40);
                        } else {
                            rvHm.setVisibility(View.GONE);
                            tvHmNot.setVisibility(View.VISIBLE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(String url, String error) {
                dismissDialog();
            }
        });
    }

    /**
     * 初始化列表
     */
    private void initRecycle() {
        rvHm.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mHouseManageAdapter = new HouseManageAdapter(this);
        mHouseManageAdapter.setOnRecycleItemClickListener(new HouseManageAdapter.OnRecycleItemClickListener() {
            @Override
            public void onItemClick(int position, int itemPosition) {
                boolean isCheck = false;
                for (int i = 0; i < mMonths.size(); i++) {
                    for (int j = 0; j < mMonths.get(i).getDays().size(); j++) {
                        if (i == position && j == itemPosition && mMonths.get(i).getDays().get(j).getState() != 4) {
                            mMonths.get(i).getDays().get(j).setSelect(!mMonths.get(i).getDays().get(j).isSelect());
                        }
                        if (mMonths.get(i).getDays().get(j).isSelect() && mMonths.get(i).getDays().get(j).getState() != 4) {
                            isCheck = true;
                        }
                    }
                }
                mHouseManageAdapter.notifyDataSetChanged();
                if (isCheck) {
                    tvHmClose.setEnabled(true);
                    tvHmManage.setEnabled(true);
                    tvHmClose.setTextColor(getResources().getColor(R.color.colorTextBlack));
                    tvHmManage.setBackgroundResource(R.drawable.shape_fe_ff40);
                } else {
                    tvHmClose.setEnabled(false);
                    tvHmManage.setEnabled(false);
                    tvHmClose.setTextColor(getResources().getColor(R.color.colorTextLight));
                    tvHmManage.setBackgroundResource(R.drawable.shape_gradient_7f_8e_40);
                }
            }
        });
        rvHm.setAdapter(mHouseManageAdapter);


    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.tv_hm_manage, R.id.tv_hm_close, R.id.ll_hm_total, R.id.ll_hm})
    public void btnOnclick(View view) {
        HashStatesEntity.BodyBean bodyBean = new HashStatesEntity.BodyBean();
        bodyBean.setMonths(mMonths);
        switch (view.getId()) {
            case R.id.tv_hm_manage://设置房态
                HouseManagePop houseManagePop = new HouseManagePop(this, 0, mHouseId, mHouseName, new Gson().toJson(bodyBean));
                houseManagePop.setOnBtnClickListener(new HouseManagePop.OnBtnClickListener() {
                    @Override
                    public void onBtnClick(boolean view) {
                        showDialog();
                        getDetails();
                    }
                });
                houseManagePop.showPopupWindow();
                break;
            case R.id.tv_hm_close:
                RefusePop phonePopular = new RefusePop(HouseManageActivity.this, "直接关房");
                phonePopular.setOnBtnClickListener(new RefusePop.OnBtnClickListener() {
                    @Override
                    public void onBtnClick(View view, String title) {
                        try {
                            showDialog();
                            List<String> dateString = new ArrayList<>();
                            int mTotalHouse = 0;//总库存
                            int mHaveHouse = 0;//已用库存
                            for (int i = 0; i < mMonths.size(); i++) {
                                for (int j = 0; j < mMonths.get(i).getDays().size(); j++) {
                                    if (mMonths.get(i).getDays().get(j).isSelect()) {
                                        mTotalHouse = mMonths.get(i).getDays().get(j).getTotalQuantity();
                                        mHaveHouse = mMonths.get(i).getDays().get(j).getUsedQuantity();
                                        dateString.add(mMonths.get(i).getDays().get(j).getDate());
                                    }
                                }
                            }
                            setPostDate(dateString, mTotalHouse, 0);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                phonePopular.showPopupWindow();
                break;
            case R.id.ll_hm_total://批量设置房态
                HouseManagePop houseManagePop1 = new HouseManagePop(this, 1, mHouseId, mHouseName, new Gson().toJson(bodyBean));
                houseManagePop1.setOnBtnClickListener(new HouseManagePop.OnBtnClickListener() {
                    @Override
                    public void onBtnClick(boolean view) {
                        showDialog();
                        getDetails();
                    }
                });
                houseManagePop1.showPopupWindow();
                break;
            case R.id.ll_hm:
                initInstallApp(mInfoBody.getHouses());
                break;
        }
    }


    private void initInstallApp(final List<HashInfosEntity.BodyBean.HousesBean> houses) {
        final ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < houses.size(); i++) {
            list.add(houses.get(i).getName());
        }
        OptionsPickerView<String> mOptionsPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                LogUtil.jLog().e(options1);
                String id = houses.get(options1).getId();
                mHouseId = id;
                tvHmHouse.setText(houses.get(options1).getName());
                showDialog();
                getDetails();
            }
        }).setCancelColor(getResources().getColor(R.color.colorRed))
                .setSubmitColor(getResources().getColor(R.color.colorRed)).build();
        for (int i = 0; i < list.size(); i++) {
            if (tvHmHouse.getText().toString().equals(list.get(i))) {
                mOptionsPickerView.setSelectOptions(i);
            }
        }
        // 设置数据
        mOptionsPickerView.setPicker(list);
        // 设置选项单位
        mOptionsPickerView.show();
    }


    /**
     * 提交后台修改数据
     */
    private void setPostDate(List<String> dateString, int mTotalHouse, int mHaveHouse) {
        Map<String, Object> map = new HashMap<>();
        HashStates hashStates = new HashStates();
        hashStates.setAction(1);
        hashStates.setDates(dateString);
        hashStates.setTotalQuantity(mTotalHouse);
        hashStates.setUsedQuantity(mHaveHouse);
        OkHttpUtil.postJson(this, String.format(Constant.URL.hashStates, SharedPreferencesUtil.getRoleInfoId(this), mHouseId), hashStates, map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    StatesPostEntity statesPostEntity = new Gson().fromJson(json, StatesPostEntity.class);
                    if (statesPostEntity.getCode().equals(Constant.Strings.SUC) && statesPostEntity.isBody()) {
                        ToastUtil.initToast(getApplicationContext(), "关房成功");
//                        showDialog();
                        getDetails();
                    } else {
                        ToastUtil.initToast(getApplicationContext(), statesPostEntity.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (mLoadDialog == null) {
            mLoadDialog = LoadDialog.newInstance("加载中");
        }
        mLoadDialog.show(getSupportFragmentManager(), "loading");
    }

    /**
     * 设置加载框
     */
    protected void dismissDialog() {
        if (mLoadDialog != null) {
            mLoadDialog.dismiss();
        }
    }
}
